package net.zjitc.controller.admin;

import net.zjitc.common.ServiceResp;
import net.zjitc.pojo.Admin;
import net.zjitc.service.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * @Author admin
 * @Date 2019/6/4 8:21
 */
@Controller
@RequestMapping(value = "/admin")
public class AgentController {
    @Autowired
    AdminService adminService;

    @RequestMapping(value = "/agent_list")
    public String agent_list(Model model){
        List<Admin>agent_list = adminService.agent_list();
        model.addAttribute("agent_list",agent_list);
        return "/admin/agent_list";
    }

    @ResponseBody   //将函数返回值作为请求返回值，没有这个注解的话，请求的响应应该是一个页面，不需要页面的话应该加上这个注解。
    @RequestMapping(value = "/checkName",method= RequestMethod.POST)
    public void checkName(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String login_name = request.getParameter("login_name");
        Admin admin = adminService.search_loginName(login_name);
        if (admin == null)
        {
            response.getWriter().print("true");
        }else {
            response.getWriter().print("false");
        }
    }

    @RequestMapping(value = "/Agent_addUI")
    public String addUI(){
        return "/admin/agent_add";
    }

    @RequestMapping(value = "/Agent_add")
    @ResponseBody
    public ServiceResp add(@RequestBody Admin admin){
        int add = adminService.add(admin);
        if (add>0)
        {
            return ServiceResp.createBySuccess("管理员添加成功",0);
        }
        return ServiceResp.createByERROR("管理员添加失败",1);
    }

    @RequestMapping(value = "/Agent_updateUI")
    public String updateUI(Model model,int id){
        Admin admin = adminService.findById(id);
        model.addAttribute("admin",admin);
        return "/admin/agent_update";
    }

    @RequestMapping(value = "/Agent_update")
    @ResponseBody
    public ServiceResp update(@RequestBody Admin admin){
        int add = adminService.update(admin);
        if (add>0)
        {
            return ServiceResp.createBySuccess("管理员修改成功",0);
        }
        return ServiceResp.createByERROR("管理员修改失败",1);
    }

    @RequestMapping("/deleteAgent")
    @ResponseBody
    public ServiceResp delete(Integer id) {
        int resultCount = adminService.deleteAgent(id);
        if (resultCount > 0) {
            return ServiceResp.createBySuccess("管理员移除成功",0);
        }
        return ServiceResp.createByERROR("管理员移除失败",1);
    }
}
